package com.lancoo.aikfc.base.control

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import java.text.DecimalFormat

/**
 * @ClassName: RunnTextView
 * @Description: java类作用描述 ：todo 数字滚动效果
 * @Author: 作者名：wgl
 * @CreateDate: 2019/2/20 11:07
 * @UpdateUser: 更新者：wgl
 * @UpdateDate: 2019/2/20 11:07
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 *
 * mTv.setValue(Float.valueOf(100),"0.0");
 *
 * <RunNumberTextView
 *         android:id="@+id/activity_main_tv"
 *         android:text="1000.00"
 *         android:layout_marginTop="10dp"
 *         android:layout_width="wrap_content"
 *         android:layout_height="wrap_content" />
 */
@SuppressLint("AppCompatCustomView")
class RunNumberTextView @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : TextView(context, attrs, defStyleAttr) {
    private var mValueAnimator: ValueAnimator? = null
    private var mDf: DecimalFormat? = null
    private fun init() {
        //格式化小数（保留小数点后两位）
        mDf = DecimalFormat("0.00")
        initAnim()
    }

    /**
     * 初始化动画
     */
    private fun initAnim() {
        mValueAnimator = ValueAnimator.ofFloat(0f, 0f)
        mValueAnimator?.duration = 1000 //动画时间为1秒
        mValueAnimator?.addUpdateListener(ValueAnimator.AnimatorUpdateListener { animation ->
            val value = animation.animatedValue as Float
            if (value > 0) {
                text = mDf?.format(animation.animatedValue as Float) //当数值大于0的时候才赋值
            }
        })
    }

    /**
     * 设置要显示的数字
     * @param value:todo 输入的数值
     * @param pattern:todo 保留的小数位数
     */
    fun setValue(value: Float, pattern: String?) {
        mDf = DecimalFormat(pattern) //todo 四舍五入
        mValueAnimator!!.setFloatValues(0f, value)
        mValueAnimator!!.start()
    }

    /**
     * 取消动画和动画监听
     */
    fun cancel() {
        mValueAnimator!!.removeAllUpdateListeners()
        mValueAnimator!!.cancel()
    }

    init {
        init()
    }
}